﻿using System;

namespace StringtoInteger
{
    public class Solution
    {
        public int MyAtoi(string str)
        {
            str = str.Trim();

            if (string.IsNullOrWhiteSpace(str))
                return 0;

            if ((str[0] != '-' && str[0] != '+') &&
                (str[0] < '0' || str[0] > '9'))
                return 0;

            try
            {
                int result = 0;
                int i = 0;
                if (str[0] == '-' || str[0] == '+')
                {
                    i = 1;
                }

                for (; i < str.Length; i++)
                {
                    if (str[i] < '0' || str[i] > '9')
                        break;

                    checked
                    {
                        result = result * 10 + (str[i] - '0');
                    }
                    
                }

                return str[0] == '-' ? -result : result;
            }
            catch (OverflowException)
            {
                return Int32.MinValue;
            }
        }
    }
}